package com.maple.design.aop.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * <p></p>
 *
 * @author maple
 * @since 2023/3/28
 */
public class CglibProxy implements MethodInterceptor {

    // 被代理的目标对象
    private Object proxyObj;

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("cglib start...");
        Object object = method.invoke(proxyObj, objects);
        System.out.println("cglib end...");
        return object;
    }

    private Object getCglibProxy(Object obj) {
        this.proxyObj = obj;
        Enhancer enhancer = new Enhancer();
        // Cglib动态代理是针对指定的类生产一个子类，在这边指定父类
        enhancer.setSuperclass(obj.getClass());
        // 回调
        enhancer.setCallback(this);
        // 返回新建的代理对象
        return enhancer.create();
    }

    public static void main(String[] args) {
        CglibProxy cglibProxy = new CglibProxy();
        // 获取代理对象
        CglibDemoServiceImpl cglibDemoService = (CglibDemoServiceImpl) cglibProxy.getCglibProxy(new CglibDemoServiceImpl());
        cglibDemoService.show("maple");
    }
}